﻿/*
 *GreyBox was written by Strategic Data Systems and licenced under the open source MS-PL. 
 */
using System;
using System.Linq;
using System.Xml.Linq;

namespace StrategicDataSystems.Cloud.Monitoring.HostedServices.ResponseToEntityMappers
{
    public class HostedServicePropertiesResponseMapper
    {

        /// <remarks>The Url element is sometimes not present in a DeploymentSlot if the deployment is in progress.</remarks>
        public HostedService MapToEntity(XDocument responseXml)
        {
            XNamespace azureNamespace = XNamespace.Get("http://schemas.microsoft.com/windowsazure");
            HostedService service = (from serviceElement in responseXml.Descendants(azureNamespace + "HostedService")
                                     select new HostedService(
                                        serviceName: serviceElement.Element(azureNamespace + "ServiceName").Value,
                                        managementUrl: new Uri(serviceElement.Element(azureNamespace + "Url").Value),
                                        deployments: from deploymentElements in serviceElement.Descendants(azureNamespace + "Deployment")
                                                    select new Deployment(
                                                        slot: deploymentElements.Element(azureNamespace + "DeploymentSlot").Value,
                                                        url: tryGetXElementValueAsUri(deploymentElements.Element(azureNamespace + "Url")), 
                                                        deploymentLabel: DecodeBase64String(deploymentElements.Element(azureNamespace + "Label").Value), 
                                                        status: deploymentElements.Element(azureNamespace + "Status").Value,
                                                        hostedServiceName: serviceElement.Element(azureNamespace + "ServiceName").Value))
                                     ).First();

            return service;
        }

        private Uri tryGetXElementValueAsUri(XElement element)
        {
            return null == element ? null : new Uri(element.Value);
        }


        private string DecodeBase64String(string str)
        {
            byte[] encodedStringBytes = Convert.FromBase64String(str);
            return System.Text.Encoding.UTF8.GetString(encodedStringBytes);
        }
    }
}
